﻿Imports System.Windows.Forms

Namespace Win
    Public Class ListViewSupport
        Public Shared Sub SaveListViewColumnsSettings(ByVal listview As ListView)
            Dim aColSizes As New Generic.List(Of Integer)
            For Each clsCol As ColumnHeader In listview.Columns
                aColSizes.Add(clsCol.Width)
            Next
            Dim strKey As String = GetListviewKey(listview)
            Dim strValue As String = Framework.Serialization.ToCommaSepString(aColSizes)
            If strValue IsNot Nothing Then Framework.Data.MetaData.SetValue(strKey, strValue)
        End Sub

        Public Shared Sub RestoreListViewColumnsSettings(ByVal listview As ListView)
            Dim strKey As String = GetListviewKey(listview)
            Dim strValue As String = Framework.Data.MetaData.GetValueAsString(strKey, Nothing)
            If strValue Is Nothing Then Return
            Dim aColSizes As Generic.List(Of Integer)
            aColSizes = Framework.Serialization.FromCommaSepIntegerString(strValue)
            For i As Integer = 0 To listview.Columns.Count - 1
                listview.Columns(i).Width = aColSizes(i)
            Next
        End Sub

        Private Shared Function GetListviewKey(ByVal listview As ListView) As String
            Dim clsSB As New System.Text.StringBuilder("LVS:")
            AppendControlName(clsSB, listview)
            Dim aColSizes As New Generic.List(Of Integer)
            For Each clsCol As ColumnHeader In listview.Columns
                clsSB.Append(clsCol.Name)
                clsSB.Append("."c)
            Next
            clsSB.Length -= 1
            Return clsSB.ToString
        End Function
        Private Shared Sub AppendControlName(ByVal buffer As System.Text.StringBuilder, ByVal control As Control)
            If control.Parent IsNot Nothing Then
                AppendControlName(buffer, control.Parent)
            End If
            buffer.Append(control.Name)
            buffer.Append("."c)
        End Sub
    End Class
End Namespace